package com.novatialabs.qttt.gwt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class QuantumTicTacToe implements EntryPoint, GameDisplayHandler {
  /**
   * The message displayed to the user when the server cannot be reached or
   * returns an error.
   */
  private static final String SERVER_ERROR = "An error occurred while "
      + "attempting to contact the server. Please check your network "
      + "connection and try again.";

  /**
   * Create a remote service proxy to talk to the server-side Greeting service.
   */
  private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

  private final Notation standardNotation = new StandardNotation();
  private GameController controller;

  private Label moveTitle;

  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {

    QuantumBoardWidget gameBoard = new QuantumBoardWidget();
    ClassicBoardWidget classicwidget = new ClassicBoardWidget();
    MoveListWidget moveListWidget = new MoveListWidget();
    moveTitle = new Label();

    GameModel game = new GameModel();
    controller = new GameController(game);
    gameBoard.addMarkHandler(controller);
    controller.addGameDisplayHandler(gameBoard);
    controller.addGameDisplayHandler(moveListWidget);
    controller.addGameDisplayHandler(classicwidget);
    controller.addGameDisplayHandler(this);

    History.addValueChangeHandler(controller.getHistoryChangeHandler());

    RootPanel.get("moveTitle").add(moveTitle);
    RootPanel.get("quantumBoard").add(gameBoard);
    RootPanel.get("moveList").add(moveListWidget);
    RootPanel.get("classicBoards").add(classicwidget);

  }

  public void display(GameDisplayEvent gameEvent) {
    moveTitle.setText(standardNotation.printGame(gameEvent.getGame()));

    String newToken = controller.getGameStateHistoryToken();
    String oldToken = History.getToken();
    if (!newToken.equals(oldToken)) {
      History.newItem(newToken);
    }
  }
}
